import Dom from '../utils/Dom';
import Utils from '../utils/index';

class Table {

   /**
    * Tabel 组件
    * @param {Dom} el 容器 
    * @param {Array} cols 数据列数组
    * @param {Array} data 数据
    * @param {Object} options 配置
    */
   constructor(el, cols, data, options) {
      this.el = el;
      this.cols = cols;
      this.options = Utils.extend({
         fixHeader: true,
         maxRow: 100,
         selectedCallback: null
      }, options);

      this.render(data);
   }

   setData(data) {

      if (this.render(data)) {
         if(data.length) {
         this.alignTables();
         }
      }
   }

   // 渲染或更新数据
   render(data) {

      // if (this.tableBody && data.length === 0) {

      //    this.tableBody.innerHTML = '<tbody><tr colspan="' + this.cols.length + '"><td style="text-align:center"><p style="padding: 10px 0">暂无数据</p></td></tr></tbody>'
      //    return false;
      // }

      let bodyStr = this.renderBody(data);


      if (!this.tableBody) {
         let headStr = this.renderHeader();
         if (this.options.fixHeader) {
            this.headTable = Dom.append(this.el, 'div', 'datatable-header', '<table>' + headStr + '</tabel>')
            this.bodyTable = Dom.append(this.el, 'div', 'datatable-body', '<table>' + bodyStr + '</table>');
            this.tableBody = this.bodyTable.childNodes[0];
            if (document.body.clientHeight < 600) {
               this.bodyTable.style['max-height'] = '200px';
            }

            if (data.length > 0) {
               setTimeout(() => {
                  this.alignTables();
               }, 100)
            }
         } else {
            this.table = Dom.append(this.el, 'table', 'datatable', headStr + bodyStr);
            this.tableBody = this.table.childNodes[1];
         }

      } else { // 更新 body 部分即可
         this.tableBody.innerHTML = bodyStr;
      }

      if (this.options.selectedCallback && Utils.isFn(this.options.selectedCallback)) {

         this.clickEvent = Dom.addEvent(this.tableBody, 'click', e => {
            let target = e.target;
            if (target.tagName === 'TD') {
               target = target.parentNode;
            }

            if (target.tagName === 'TR' && target.getAttribute('data-index') !== undefined) {
               this.clearSelection();
               target.className += ' selected';
               if (this.options) {
                  this.options.selectedCallback(target);
               }
            }
            return Dom.nodefault(e);
         });
      }

      return true;
   }

   // 对齐表格
   alignTables() {
      let colgroup = '',
         tdWidth = null;

      this.tableBody.childNodes[0].childNodes[0].childNodes.forEach((td, index) => {
         tdWidth = this.cols[index].width;
         if (!tdWidth) {
            tdWidth = parseInt(Dom.getStyles(td, 'width').replace('px', ''));
         }
         colgroup += '<col width="' + tdWidth + '">';
      });
      colgroup += '<col>';
      if (this.headTable.childNodes[0].childNodes.length === 1) {
         this.headTable.childNodes[0].innerHTML += '<colgroup>' + colgroup + '</colgroup>';
      } else {
         this.headTable.childNodes[0].childNodes[1].innerHTML = colgroup;
      }
      if (this.tableBody.childNodes.length === 1) {
         this.tableBody.innerHTML += '<colgroup>' + colgroup + '</colgroup>';
      } else {
         this.tableBody.childNodes[1].innerHTML = colgroup;
      }
   }

   // 渲染表头，计算表头的 html
   renderHeader() {
      let str = '<thead><tr>';
      this.cols.forEach(col => {
         str += '<th' + (col.width ? (' with="' + col.width + '"') : '') + '>' + col.name + '</th>';
      });
      str += '</tr></thead>';
      return str;
   }

   // 渲染表格主题部分的 html
   renderBody(data) {
      if (data.length === 0) {
         return '<tbody><tr><td style="text-align:center" colspan="' + this.cols.length + '"><p style="padding: 10px 0">暂无数据</p></td></tr></tbody>';
      }
      let str = '<tbody>',
         trValue = '';
      data.forEach((d, i) => {
         if (this.options.trValueKey && d[this.options.trValueKey] != undefined) {
            trValue = 'data-' + this.options.trValueKey + '="' + d[this.options.trValueKey] + '"';
         } else {
            trValue = '';
         }
         str += '<tr data-index="' + i + '" ' + trValue + '>';
         this.cols.forEach(col => {
            str += '<td>' + (d[col.key] || '') + '</td>'
         });
         str += '</tr>';
      });

      str += '</tbody>';
      return str;
   }

   destory() {
      this.el.innerHTML = '';
      if (this.clickEvent) {
         this.clickEvent();
         this.clickEvent = null;
      }
      this.cols = null;
      this.options = null;
   }

   clearSelection() {
      if (this.tableBody) {
         let i = 0,
            total = this.tableBody.childNodes[0].childNodes.length,
            tr = null;
         for (; i < total; i++) {
            tr = this.tableBody.childNodes[0].childNodes[i];
            if (tr.className && tr.className.indexOf('selected') !== -1) {
               tr.className = tr.className.replace(' selected', '');
               break;
            }
         }
      }
   }
}

export default Table;